///**
// * ElasticSearchDAO.java 
// * Copyright © 2014-2016, 杭州泊享网络科技有限公司
// * 
// * @author Liu Tao
// * @create 2015年7月15日
// */
//package com.pshare.framework.dao.es;
//
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.Iterator;
//import java.util.List;
//import java.util.Map;
//
//import javax.annotation.PostConstruct;
//
//import org.apache.log4j.Logger;
//import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
//import org.elasticsearch.action.delete.DeleteResponse;
//import org.elasticsearch.action.get.GetResponse;
//import org.elasticsearch.action.index.IndexResponse;
//import org.elasticsearch.action.search.SearchResponse;
//import org.elasticsearch.action.update.UpdateRequestBuilder;
//import org.elasticsearch.client.Requests;
//import org.elasticsearch.client.transport.TransportClient;
//import org.elasticsearch.common.geo.GeoPoint;
//import org.elasticsearch.common.settings.ImmutableSettings;
//import org.elasticsearch.common.settings.Settings;
//import org.elasticsearch.common.transport.InetSocketTransportAddress;
//import org.elasticsearch.common.xcontent.XContentBuilder;
//import org.elasticsearch.common.xcontent.XContentFactory;
//import org.elasticsearch.index.query.FilterBuilders;
//import org.elasticsearch.index.query.GeoBoundingBoxFilterBuilder;
//import org.elasticsearch.index.query.QueryBuilders;
//import org.elasticsearch.index.query.RangeFilterBuilder;
//import org.elasticsearch.search.SearchHit;
//import org.elasticsearch.search.aggregations.AggregationBuilders;
//import org.elasticsearch.search.aggregations.bucket.filter.InternalFilter;
//import org.elasticsearch.search.aggregations.bucket.geogrid.GeoHashGrid.Bucket;
//import org.elasticsearch.search.aggregations.bucket.geogrid.InternalGeoHashGrid;
//
//import com.fasterxml.jackson.core.JsonProcessingException;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.google.gson.Gson;
//import com.google.gson.GsonBuilder;
//import com.google.gson.JsonObject;
//import com.pshare.constant.SeaxConstants;
//import com.pshare.framework.bean.MapAggregation;
//import com.pshare.framework.query.MapQueryInfo;
//import com.pshare.util.SearchPropertyUtils;
//
//import aj.org.objectweb.asm.Type;
//
///**
// * ES持久层
// */
//public class ElasticSearchDAO {
//	
//	private static final Logger logger = Logger.getLogger(ElasticSearchDAO.class);
//
//	protected String INDEX_NAME;
//	protected String TYPE;
//	protected static final String ES_CLUSTER_SERVERS = SearchPropertyUtils.getProperty("es.cluster.servers");
//	protected static final String ES_CLUSTER_NAME = SearchPropertyUtils.getProperty("es.cluster.name");
//	protected static final Integer MAX_DISTNACE = Integer.parseInt(SearchPropertyUtils.getProperty("max_distance"));
//	protected static final Integer PRECISION = 4;
//	
//	protected TransportClient client;
//
//	//@PostConstruct
//	private void init() {
//		Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", ES_CLUSTER_NAME).build();
//		client = new TransportClient(settings);
//
//		String[] esClusterServers = ES_CLUSTER_SERVERS.split(SeaxConstants.COMMA);
//		for (String es : esClusterServers) {
//			String[] esInfo = es.split(SeaxConstants.COLON);
//			client.addTransportAddress(new InetSocketTransportAddress(esInfo[0], Integer.parseInt(esInfo[1])));
//		}
//	}
//
//	/**
//	 * 地图模式下聚合查询
//	 * 
//	 * @param queryInfo
//	 * @return List<MapAggregation>
//	 */
//	public List<MapAggregation> mapAggQuery(MapQueryInfo queryInfo) {
//		List<MapAggregation> list = new ArrayList<MapAggregation>();
//		SearchResponse sr = client
//				.prepareSearch(INDEX_NAME)
//				.setTypes(TYPE)
//				.setQuery(QueryBuilders.matchAllQuery())
//				.addAggregation(
//						AggregationBuilders
//								.filter("filter")
//								.filter(FilterBuilders.geoBoundingBoxFilter("location").topLeft(queryInfo.getTopLeftLat(), queryInfo.getTopLeftLon())
//										.bottomRight(queryInfo.getBottomRightLat(), queryInfo.getBottomRightLon()))
//								.subAggregation(
//										AggregationBuilders.geohashGrid("zoom").field("location").precision(PRECISION)))
//				.execute().actionGet();
//
//		InternalFilter filter = sr.getAggregations().get("filter");
//		long docCount = filter.getDocCount();
//		if (docCount > 0) {
//			InternalGeoHashGrid zoom = filter.getAggregations().get("zoom");
//			for (Bucket bk : zoom.getBuckets()) {
//				long count = bk.getDocCount();
//				GeoPoint location = bk.getKeyAsGeoPoint();
//				list.add(new MapAggregation(location.getLon(), location.getLat(), count));
//			}
//		}
//
//		return list;
//	}
//
//	/**
//	 * 地图模式下详细数据查询
//	 * 
//	 * @param queryInfo
//	 * @param c
//	 * @return List<T>
//	 */
//	public <T> List<T> mapQuery(MapQueryInfo queryInfo, Class<T> c) {
//		GeoBoundingBoxFilterBuilder fb= FilterBuilders.geoBoundingBoxFilter("location").topLeft(queryInfo.getTopLeftLat(), queryInfo.getTopLeftLon()).bottomRight(queryInfo.getBottomRightLat(), queryInfo.getBottomRightLon());
//		
//		SearchResponse searchResponse = client
//				.prepareSearch(INDEX_NAME)
//				.setTypes(TYPE)
//				.setQuery(QueryBuilders.matchAllQuery())
//				//.setPostFilter(fb)
//				.execute().actionGet();
//
//		List<T> list = new ArrayList<T>();
//		for (SearchHit hit : searchResponse.getHits().getHits()) {
//			T obj = sourceToObject(hit.getSource(), c);
//			list.add(obj);
//		}
//
//		return list;
//	}
//
//	/**
//	 * 新增数据
//	 * @param bean
//	 * @param id
//	 */
//	public <T> void add(T bean, Long id) {
//		
//		String json = new Gson().toJson(bean);
//		
//		// 得到一个json串
//		IndexResponse ir = client.prepareIndex(INDEX_NAME, TYPE, id + "").setSource(json).execute()
//				.actionGet();
//
//		String index_name = ir.getIndex();
//		String index_type = ir.getType();
//		String docid = ir.getId();
//		long version = ir.getVersion();
//
//		logger.info(index_name + " -- " + index_type + " -- " + docid + " -- " + version);
//	}
//
//	/**
//	 * 删除数据
//	 * @param id
//	 */
//	public void delete(Long id) {
//		try {
//			DeleteResponse de = client.prepareDelete(INDEX_NAME, TYPE, id + "").execute().actionGet();
//			if (!de.isFound()) {
//				logger.error("can not find document");
//			} else {
//				logger.info("deleted document");
//			}
//		} catch (Exception e) {
//			logger.error(e.getMessage(), e);
//		}
//	}
//
//	/**
//	 * 更新数据
//	 * @param bean
//	 * @param id
//	 */
//	public void update(Object bean, Long id) {
//		UpdateRequestBuilder updateRequestBuilder = client.prepareUpdate(INDEX_NAME, TYPE, id + "");    
//		updateRequestBuilder.setDoc(new Gson().toJson(bean));   
//		updateRequestBuilder.execute().actionGet(); 
//		logger.info("update document successful");
//	}
//
//	/**
//	 * 读取单条数据
//	 * @param id
//	 * @return boolean
//	 */
//	public <T> T get(Long id, Class<T> c) {
//		GetResponse response = client.prepareGet(INDEX_NAME, TYPE, id + "").execute().actionGet();
//		if (!response.isExists()) {
//			logger.warn("can not find document");
//			return null;
//		}
//		
//		T bean = sourceToObject(response.getSource(), c);
//		return bean;
//	}
//	
//	private <T> T sourceToObject(Map<String, Object> source,Class<T> c){
//		
//        ObjectMapper mapper=new ObjectMapper();
//        try {
//			String json=mapper.writeValueAsString(source);
//	        return new Gson().fromJson(json, c);
//		} catch (JsonProcessingException e) {
//			
//		}
//        return null;
//	}
//}
